# -*- coding: utf-8 -*-
import os

from bottle import (
    Bottle,
    request,
    abort,
    static_file,
    FileUpload
)

from .. import (
    root_dir,
    static_dir,
    upload_dir,
    templates_dir
)


file_app = Bottle()

@file_app.route('/static/<filename:path>')
def server_static(filename):
    file_path = os.path.join(static_dir, filename)
    if os.path.exists(file_path):
        return static_file(filename, root=static_dir)
    else:
        abort(404, "File Not Found")

@file_app.route('/favicon.ico')
def server_static():
    filename = 'favicon.ico'
    file_path = os.path.join(static_dir, filename)
    if os.path.exists(file_path):
        return static_file(filename, root=static_dir)
    else:
        abort(404, "File Not Found")

@file_app.get('/upload')
def file_upload_view():
    return ''.join([
    '<form action="/upload" method="post" enctype="multipart/form-data">',
        '<input type="hidden" name="field" value="upload" />',
        'Select a file: <input type="file" name="upload" /><br />',
        '<input type="submit" value="Start upload" />',
    '</form>'
    ])

@file_app.post('/upload')
def file_upload():
    field = request.forms.get('field', None)
    if bool(field):
        upload = request.files.get(field, None)
        if isinstance(upload, FileUpload):
            name, ext = os.path.splitext(upload.filename)
            # if ext not in ('.png','.jpg','.jpeg'):
            #     return 'File extension not allowed.'
            save_path = os.path.join(upload_dir, upload.filename)
            upload.save(save_path) # appends upload.filename automatically
            return 'OK'
        else:
            return 'No uploaded file found'
    else:
        return 'parameter `field` not found'